package guigu.IoSystem;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 测试FileInputSteam和FileOutputStream的使用
 *
 * 结论：
 * 1. 对于文本文件(.txt、.java、.c、.cpp)，使用字符流处理
 * 2. 对于非文本文件(.jpg、.mp3、.mp4、.doc、.ppt)，使用字节流处理
 */
public class FileInputStreamTest {
    @Test
    public void test1()
    {
        /*
        不要用字节流操作文本文件
         */
        //1.造文件
        FileInputStream fileInputStream = null;
        try {
            File file = new File("hello.txt");
            //2.造流
            fileInputStream = new FileInputStream(file);
            //3.读数据
            byte buffer[] = new byte[5];
            int len;//记录每次读取的字节的个数
            while((len=fileInputStream.read(buffer))!=-1)
            {
                String str = new String(buffer,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileInputStream!=null)
            {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void test2()
    {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            File srcFile = new File("微信图片_20220828222640.jpg");
            File destFile = new File("微信图片_202208282226401.jpg");
            fileInputStream = new FileInputStream(srcFile);
            fileOutputStream = new FileOutputStream(destFile);
            byte buffer[] = new byte[1024];
            int len;
            while ((len = fileInputStream.read(buffer))!=-1)
            {
                fileOutputStream.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileInputStream!=null)
            {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fileOutputStream!=null)
            {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
